// 音乐播放器管理类
class MusicPlayer {
  constructor() {
    this.audioContext = null
    this.currentSong = null
    this.isPlaying = false
    this.currentTime = 0
    this.duration = 0
    this.playlist = []
    this.currentIndex = 0
    this.listeners = {}
    this.retryCount = 0
    this.maxRetries = 3
  }

  // 初始化播放器
  init() {
    this.audioContext = uni.createInnerAudioContext()
    
    // 监听播放事件
    this.audioContext.onPlay(() => {
      this.isPlaying = true
      this.retryCount = 0 // 重置重试计数
      this.emit('play')
    })

    this.audioContext.onPause(() => {
      this.isPlaying = false
      this.emit('pause')
    })

    this.audioContext.onStop(() => {
      this.isPlaying = false
      this.emit('stop')
    })

    this.audioContext.onEnded(() => {
      this.isPlaying = false
      this.next()
    })

    this.audioContext.onTimeUpdate(() => {
      this.currentTime = this.audioContext.currentTime
      this.emit('timeUpdate', {
        currentTime: this.currentTime,
        duration: this.duration
      })
    })

    this.audioContext.onCanplay(() => {
      this.duration = this.audioContext.duration
      this.emit('canplay')
    })

    this.audioContext.onError((error) => {
      console.error('播放器错误:', error)
      this.handlePlaybackError(error)
      this.emit('error', error)
    })
  }

  // 处理播放错误
  async handlePlaybackError(error) {
    console.error('音频播放错误:', error)
    
    // 如果还有重试次数，尝试重新播放
    if (this.retryCount < this.maxRetries && this.currentSong) {
      this.retryCount++
      console.log(`尝试重新播放 (${this.retryCount}/${this.maxRetries})`)
      
      // 等待1秒后重试
      await new Promise(resolve => setTimeout(resolve, 1000))
      this.play(this.currentSong)
    } else {
      // 重试次数用完，显示错误信息
      uni.showToast({
        title: '音频播放失败，请检查网络或音频文件',
        icon: 'none',
        duration: 3000
      })
      
      // 重置重试计数
      this.retryCount = 0
    }
  }

  // 播放歌曲
  play(song) {
    if (!song) return

    this.currentSong = song
    
    // 验证音频URL
    if (!song.file_url || song.file_url.trim() === '') {
      console.error('无效的音频文件URL:', song)
      uni.showToast({
        title: '音频文件路径无效',
        icon: 'none'
      })
      return
    }
    
    console.log('正在播放音频:', song.file_url)
    
    this.audioContext.src = song.file_url
    this.audioContext.title = song.name
    this.audioContext.singer = song.artist_name
    this.audioContext.coverImgUrl = song.cover_image_url
    
    this.audioContext.play()
  }

  // 暂停/恢复播放
  togglePlay() {
    if (this.isPlaying) {
      this.audioContext.pause()
    } else {
      if (this.currentSong) {
        this.audioContext.play()
      } else if (this.playlist.length > 0) {
        // 如果没有当前歌曲但有播放列表，播放第一首
        this.play(this.playlist[0])
      }
    }
  }

  // 停止播放
  stop() {
    this.audioContext.stop()
  }

  // 设置播放时间
  seek(time) {
    this.audioContext.seek(time)
  }

  // 上一首
  prev() {
    if (this.playlist.length === 0) return
    
    this.currentIndex = this.currentIndex > 0 ? this.currentIndex - 1 : this.playlist.length - 1
    this.play(this.playlist[this.currentIndex])
  }

  // 下一首
  next() {
    if (this.playlist.length === 0) return
    
    this.currentIndex = this.currentIndex < this.playlist.length - 1 ? this.currentIndex + 1 : 0
    this.play(this.playlist[this.currentIndex])
  }

  // 设置播放列表
  setPlaylist(playlist, index = 0) {
    this.playlist = playlist
    this.currentIndex = index
    if (playlist.length > 0) {
      this.play(playlist[index])
    }
  }

  // 添加歌曲到播放列表
  addToPlaylist(song) {
    this.playlist.push(song)
  }

  // 移除播放列表中的歌曲
  removeFromPlaylist(index) {
    this.playlist.splice(index, 1)
    if (index < this.currentIndex) {
      this.currentIndex--
    } else if (index === this.currentIndex && this.playlist.length > 0) {
      this.play(this.playlist[this.currentIndex])
    }
  }

  // 清空播放列表
  clearPlaylist() {
    this.playlist = []
    this.currentIndex = 0
    this.stop()
  }

  // 获取当前播放信息
  getCurrentInfo() {
    return {
      song: this.currentSong,
      isPlaying: this.isPlaying,
      currentTime: this.currentTime,
      duration: this.duration,
      playlist: this.playlist,
      currentIndex: this.currentIndex
    }
  }

  // 事件监听
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = []
    }
    this.listeners[event].push(callback)
  }

  // 移除事件监听
  off(event, callback) {
    if (this.listeners[event]) {
      const index = this.listeners[event].indexOf(callback)
      if (index > -1) {
        this.listeners[event].splice(index, 1)
      }
    }
  }

  // 触发事件
  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(data))
    }
  }

  // 销毁播放器
  destroy() {
    if (this.audioContext) {
      this.audioContext.destroy()
      this.audioContext = null
    }
    this.listeners = {}
  }
}

// 创建全局播放器实例
const musicPlayer = new MusicPlayer()

export default musicPlayer